const express = require('express');
const Mock = require('mockjs');
const fs = require('fs');
const path = require('path');
const app = express();
const bodyParser = require('body-parser');
const port = 1800;
//获取POST参数转body对象
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

/*为app添加中间件处理跨域请求*/
app.use(function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.header('Access-Control-Allow-Headers', 'Content-Type');
    next();
});

// 返回数据
function callbackRes(req, res, item) {
    if (typeof item.res === "function") {
        res.json(item.res(req));
    } else {
        res.json(item.res);
    }
}

// 递归获取目录下的所有文件
function getFiles(dir, filesList = []) {
    const files = fs.readdirSync(dir);
    files.forEach(file => {
        const filePath = path.join(dir, file);
        if (fs.statSync(filePath).isDirectory()) {
            getFiles(filePath, filesList); // 递归遍历子目录
        } else {
            filesList.push(filePath);
        }
    });
    return filesList;
}

const mockFiles = getFiles(path.join(__dirname, 'http'));

// 为每个具体的配置创建监听
mockFiles.forEach(file => {
    const item = require(`${file}`);
    app.all(item.url, function (req, res) {
        if (item.method) {
            if (item.method.indexOf(req.method) > -1) {
                callbackRes(req, res, item);
            } else {
                res.json({
                    "code": 0,
                    "data": '请求method类型不匹配,请检查',
                    "msg": "success"
                })
            }
        } else {
            callbackRes(req, res, item);
        }
    });
});

//监听端口
app.listen(port);

console.log('Open:http://localhost:'+port);